import React from 'react';
import './settings.less';
import { emailRegular } from '../../../utils/regular';
import { Modal } from 'antd';

class Settings extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            modalContent: '',
            isModalOpen: false,
            isClearModalOpen: false,
            clearConfirmed: false,
        };
    }

    validateEmail = (email) => {
        return emailRegular.reg.test(email) ? '' : emailRegular.msg;
    };

    handleConfirm = async () => {
        const { email, password } = this.state;
        const errorMessage = this.validateEmail(email);
        if (errorMessage) {
            this.setState({ modalContent: errorMessage, isModalOpen: true });
        } else if (password.length > 0) {
            try {
                this.setState({ modalContent: '登录成功，正在加载邮箱内容...', isModalOpen: true });
            } catch (error) {
                this.setState({ modalContent: error.message || '登录失败', isModalOpen: true });
            }
        } else {
            this.setState({ modalContent: '密码不能为空', isModalOpen: true });
        }
    };

    handleClear = () => {
        this.setState({ modalContent: '确定要清空吗？', isClearModalOpen: true });
    };

    handleClearConfirm = () => {
        this.setState({
            email: '',
            password: '',
            clearConfirmed: true,
            isClearModalOpen: false,
        });
    };

    handleClearCancel = () => {
        this.setState({ isClearModalOpen: false });
    };

    render() {
        const { email, password, modalContent, isModalOpen, isClearModalOpen } = this.state;
        return (
            <div className='settings-all'>
                <h1>设置</h1>
                <div className='settings-main'>
                    <p>邮箱名称: <input value={email} onChange={(e) => this.setState({ email: e.target.value })} /></p>
                    <p>邮箱密码: <input type="password" value={password} onChange={(e) => this.setState({ password: e.target.value })} /></p>
                </div>
                <div className='button-container'>
                    <button onClick={this.handleConfirm}>确定</button>
                    <button onClick={this.handleClear}>清空</button>
                </div>

                <Modal title="提示" visible={isModalOpen} onOk={() => this.setState({ isModalOpen: false })} onCancel={() => this.setState({ isModalOpen: false })}>
                    <p>{modalContent}</p>
                </Modal>

                <Modal title="确认清空" visible={isClearModalOpen} onOk={this.handleClearConfirm} onCancel={this.handleClearCancel}>
                    <p>确定要清空输入吗？</p>
                </Modal>
            </div>
        );
    }
}

export default Settings;